﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using TestSystem.Model;
using Microsoft.EntityFrameworkCore;

namespace TestSystem.ViewModel.CURD.WebUserVMs
{
    public partial class WebUserVM : BaseCRUDVM<WebUser>
    {
        public List<ComboSelectListItem> AllUnitWorks { get; set; }
        public List<ComboSelectListItem> AllUserRoless { get; set; }
        [Display(Name = "角色")]
        public List<Guid> SelectedUserRolesIDs { get; set; }

        public WebUserVM()
        {
            SetInclude(x => x.UnitWork);
            SetInclude(x => x.UserRoles);
        }

        protected override void InitVM()
        {
            AllUnitWorks = DC.Set<UnitWork>().GetSelectListItems(LoginUserInfo?.DataPrivileges, null, y => y.UnitWorkName);
            AllUserRoless = DC.Set<FrameworkRole>().GetSelectListItems(LoginUserInfo?.DataPrivileges, null, y => y.RoleName);
            SelectedUserRolesIDs = Entity.UserRoles?.Select(x => x.RoleId).ToList();
        }

        public override void DoAdd()
        {
            Entity.UserRoles = new List<FrameworkUserRole>();
            if (SelectedUserRolesIDs != null)
            {
                foreach (var id in SelectedUserRolesIDs)
                {
                    Entity.UserRoles.Add(new FrameworkUserRole { RoleId = id });
                }
            }
            Entity.Password = Utils.GetMD5String(Entity.Password);
            base.DoAdd();
        }

        public override void DoEdit(bool updateAllFields = false)
        {
            var user = DC.Set<WebUser>().AsNoTracking().SingleOrDefault(x => x.ID == Entity.ID);
            Entity.UserRoles = new List<FrameworkUserRole>();
            if(SelectedUserRolesIDs != null )
            {
                SelectedUserRolesIDs.ForEach(x => Entity.UserRoles.Add(new FrameworkUserRole { ID = Guid.NewGuid(), RoleId = x }));
            }
            if (Entity.Password != user.Password)
            {
                Entity.Password = Utils.GetMD5String(Entity.Password);
            }

            base.DoEdit(updateAllFields);
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }
    }
}
